/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkMediaConsumer.h"
#include "MkUtil/MkUtil.h"

CMkMediaConsume::CMkMediaConsume(const MkMediaConsumeType& ConsumeType)
    : m_ConsumeType(ConsumeType)
{
}

Uint32 CMkMediaConsume::AddConsumer(CMkMediaConsumer* pConsumer, const MkString& ConsumerId/* = ""*/)
{
    if (m_ConsumeType != pConsumer->GetConsumeType()) {
        return InvalidParams;
    }
    MkString SessionId = ConsumerId;
    if (ConsumerId.empty()) {
        SessionId = pConsumer->GetConsumerId();
    }
    m_MapConsumer[SessionId] = pConsumer;
    return NoneError;
}

Uint32 CMkMediaConsume::DeleteConsumer(const MkString& ConsumerId)
{
    Uint32 ErrorCode = InvalidSession;
    MkMap<MkString, CMkMediaConsumer*>::iterator it = m_MapConsumer.find(ConsumerId);
    if (it != m_MapConsumer.end()) {
        ErrorCode = NoneError;
        m_MapConsumer.erase(it);
    }
    return ErrorCode;
}

Uint32 CMkMediaConsume::GetConsumer(const MkString& ConsumerId, CMkMediaConsumer** ppConsumer)
{
    Uint32 ErrorCode = InvalidSession;
    MkMap<MkString, CMkMediaConsumer*>::iterator it = m_MapConsumer.find(ConsumerId);
    if (it != m_MapConsumer.end()) {
        *ppConsumer = it->second;
        ErrorCode = NoneError;
    }
    return ErrorCode;
}

void CMkMediaConsume::ClearConsumer()
{
    MkMap<MkString, CMkMediaConsumer*>::iterator it = m_MapConsumer.begin();
    for (; it != m_MapConsumer.end(); it++) {
        if (it->second) {
            it->second->Release();
        }
    }
    m_MapConsumer.clear();
}

CMkMediaConsumer::CMkMediaConsumer(const MkMediaConsumeType& ConumseType)
    : m_ConsumeType(ConumseType)
    , m_bFirstSend(TRUE)
    , m_SendBytes(0)
    , m_StartTime(NowMkTime)
{
    CMkUtil::CreateRandomString(Len16, m_ConsumerId);
}

CMkMediaConsume::~CMkMediaConsume()
{
    m_MapConsumer.clear();
}

CMkMediaConsumer::~CMkMediaConsumer()
{

}